package manager.modulo.ferramenta.fonte;

import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.AutoComplete;
import manager.auxiliares.Configurations;
import manager.auxiliares.FixedLengthDocument;
import manager.auxiliares.Format;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.fonte.JanelaLogin;
import manager.interfaces.InterfaceTable;
import manager.modulo.ferramenta.dao.FerramentaDao;
import manager.modulo.ferramenta.dao.FerramentaHistoricoDao;
import manager.modulo.ferramenta.dao.HistoricoFerramentaDao;
import manager.modulo.ferramenta.enumerator.EnumSituacaoFerramenta;
import manager.modulo.ferramenta.enumerator.EnumSituacaoFerramentaHistorico.SituacaoFerramentaHistoricoFerramenta;
import manager.modulo.ferramenta.enumerator.EnumSituacaoHistoricoFerramenta;
import manager.modulo.ferramenta.enumerator.EnumSituacaoHistoricoFerramenta.SituacaoHistoricoFerramenta;
import manager.modulo.funcionario.dao.FuncionarioDao;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Thiago
 */
public class JanelaHistoricoFerramenta extends javax.swing.JFrame {

    //Histórico Ferramenta
    int idHistoricoFerramenta = 0;
    AutoComplete autoCompletarFuncionario;
    //Ferramentas
    int idFerramenta = 0;
    int index = 0;
    TableModel tableModel;
    TableRender tableRender;
    TableRowSorter tableRowSorter;
    LinkedList<FerramentaDao> listaFerramentas;
    AutoComplete autoCompletarIdentificadorFerramenta;
    AutoComplete autoCompletarNomeFerramenta;

    public JanelaHistoricoFerramenta() {
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaHistoricoFerramenta(int id) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idHistoricoFerramenta = id;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private LinkedList<String> getNomeColunasTabelaFerramenta() {
        LinkedList<String> columnNames = new LinkedList<String>();
        columnNames.add("");
        columnNames.add("Identificador");
        columnNames.add("Ferramenta");
        columnNames.add("Situação");
        return columnNames;
    }

    private void carregarInformacoesFerramenta() {
        jButton2.setToolTipText("Editar");
        jButton2.setIcon(new Icons().getEdit());
        jButton2.setEnabled(false);
        jButton4.setEnabled(true);
        jButton3.setEnabled(true);


        FerramentaDao ferramentaDao = listaFerramentas.get(index);
        jTextField8.setText(ferramentaDao.getIdentificador());
        jTextField5.setText(ferramentaDao.getNome());
        autoCompletarIdentificadorFerramenta.getjScrollPane().setVisible(false);
        autoCompletarNomeFerramenta.getjScrollPane().setVisible(false);
    }

    private void configureTable() {
        tableRender = new TableRender();
        tableModel = new TableModel(getNomeColunasTabelaFerramenta(), tableRender, new InterfaceTable() {
            public void tableAction(int id, int columnIndex, int rowIndex) {
                if (columnIndex < 0) {
                    if (idHistoricoFerramenta == 0) {
                        index = rowIndex;
                        carregarInformacoesFerramenta();
                    }
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(0).setMinWidth(30);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setMaxWidth(60);
        jTable1.getColumnModel().getColumn(3).setMinWidth(60);
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorter = tableRowComparator;
        jTable1.setRowSelectionAllowed(false);

        buscarTabela();
    }

    private void configurarCamposHistoricoFerramentas() {
        ((TextFieldValidator) jTextField1).validarCampo();
        ((FormatedFieldValidator) jFormattedTextField1).validarCampo();
        ((FormatedFieldValidator) jFormattedTextField2).validarCampo();
        ((TextFieldValidator) jTextField4).validarCampo();
        configurarCamposFerramentas();
    }

    private void configurarCamposFerramentas() {
        if (jRadioButton1.isSelected()) {
            ((TextFieldValidator) jTextField8).validarCampo();
            jLabel8.setForeground(Configurations.getFieldValidationOk());
        } else {
            ((TextFieldValidator) jTextField5).validarCampo();
            jLabel13.setForeground(Configurations.getFieldValidationOk());
        }
    }

    private void limparCamposFerramentas() {
        idFerramenta = 0;
        index = 0;

        jTextField8.setText("");
        jTextField5.setText("");
        jScrollPane3.setVisible(false);

        jButton2.setToolTipText("Adicionar");
        jButton2.setIcon(new Icons().getAdd());
        jButton2.setEnabled(true);
        jButton3.setEnabled(false);
        jButton4.setEnabled(false);

        configurarCamposFerramentas();
    }

    private void buscarTabela() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> columnId = new LinkedList<Integer>();
        LinkedList<String> colunaIdentificador = new LinkedList<String>();
        LinkedList<String> colunaFerramenta = new LinkedList<String>();
        LinkedList<String> colunaSituacao = new LinkedList<String>();

        for (int i = 0; i < listaFerramentas.size(); i++) {
            FerramentaDao ferramentaDao = listaFerramentas.get(i);
            columnId.add(i);
            colunaIdentificador.add(ferramentaDao.getIdentificador());
            colunaFerramenta.add(ferramentaDao.getNome());
            colunaSituacao.add(EnumSituacaoFerramenta.ConvertEnumString(ferramentaDao.getSituacao()));
        }

        if (listaFerramentas.size() > 0) {
            searchResult.add(columnId);
            searchResult.add(Format.getBooleanLinkedList(columnId.size()));
            searchResult.add(colunaIdentificador);
            searchResult.add(colunaFerramenta);
            searchResult.add(colunaSituacao);
        }

        tableModel.update(searchResult);
        jTable1.setDefaultRenderer(Object.class, tableRender);
        tableRowSorter.setModel(tableModel);

        jTable1.setRowSorter(tableRowSorter);
    }

    private LinkedList<String> validarCamposHistoricoFerramentas() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField1).validarCampo() || FuncionarioDao.getIdFuncionarioByIdentificador(jTextField1.getText()) == 0) {// Funcionário
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField1).validarCampo()) {// Data de Entrega
            fieldList.add(((FormatedFieldValidator) jFormattedTextField1).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField2).validarCampo()) {// Data de Previsão Devolução
            fieldList.add(((FormatedFieldValidator) jFormattedTextField2).getjLabel().getText());
        }
        if (idHistoricoFerramenta != 0) {
            if (!((FormatedFieldValidator) jFormattedTextField5).validarCampo()) {// Data de Devolução
                fieldList.add(((FormatedFieldValidator) jFormattedTextField5).getjLabel().getText());
            }
        }
        if (!((TextFieldValidator) jTextField4).validarCampo() || FuncionarioDao.getIdFuncionarioByIdentificador(jTextField1.getText()) == 0) {// Justificativa
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        return fieldList;
    }

    private LinkedList<String> valid() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField1).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField4).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField1).validarCampo()) {
            fieldList.add(((FormatedFieldValidator) jFormattedTextField1).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField2).validarCampo()) {
            fieldList.add(((FormatedFieldValidator) jFormattedTextField2).getjLabel().getText());
        }
        return fieldList;
    }

    private int adicionarHistorioFerramenta() {
        try {
            try {
                JanelaLogin.connection.setAutoCommit(false);

                FuncionarioDao funcionarioDao = new FuncionarioDao();
                funcionarioDao.buscar(FuncionarioDao.getIdFuncionarioByIdentificador(jTextField1.getText()));

                HistoricoFerramentaDao historicoFerramentaDao = new HistoricoFerramentaDao();
                historicoFerramentaDao.setIdFuncionario(funcionarioDao.getId());
                historicoFerramentaDao.setDtEntrega(Format.formatVisualDateToTimestamp(jFormattedTextField1.getText()));
                historicoFerramentaDao.setDtPrevisaoDevolucao(Format.formatVisualDateToTimestamp(jFormattedTextField2.getText()));
                historicoFerramentaDao.setDtDevolucao(null);
                historicoFerramentaDao.setSituacao(EnumSituacaoHistoricoFerramenta.ConvertStringEnum(jComboBox3.getSelectedItem().toString()));
                historicoFerramentaDao.setJustificativa(jTextField4.getText());
                historicoFerramentaDao.setObservacao(jTextArea1.getText());
                historicoFerramentaDao.inserir();

                for (int i = 0; i < listaFerramentas.size(); i++) {
                    FerramentaDao ferramentaDao = listaFerramentas.get(i);
                    if (ferramentaDao.getIdFuncionario() == 0) {
                        ferramentaDao.setIdFuncionario(historicoFerramentaDao.getIdFuncionario());
                        ferramentaDao.atualizar();

                        FerramentaHistoricoDao ferramentaHistoricoDao = new FerramentaHistoricoDao();
                        ferramentaHistoricoDao.setIdFerramenta(ferramentaDao.getId());
                        ferramentaHistoricoDao.setIdHistoricoFerramenta(historicoFerramentaDao.getId());
                        ferramentaHistoricoDao.setSituacao(SituacaoFerramentaHistoricoFerramenta.ATIVADO);
                        ferramentaHistoricoDao.inserir();
                    } else {
                        JOptionPane.showMessageDialog(null, "Existe uma ferramenta selecionada que não está diponível no estoque.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                        throw new Exception("Ferramenta não está disponível");
                    }
                }

                Object[] options = {"Sim", "Não"};
                int j = JOptionPane.showOptionDialog(null, "Deseja imprimir este registro de Histórico de Ferramenta?", "Histórico de Ferramentas", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                if (j == JOptionPane.YES_OPTION) {
                    this.imprimir(historicoFerramentaDao.getId());
                }

                JanelaLogin.connection.commit();
                JOptionPane.showMessageDialog(null, "Histórico de ferramentas cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private void editarHistoricoFerramenta() {
        try {
            try {
                JanelaLogin.connection.setAutoCommit(false);

                HistoricoFerramentaDao historicoFerramentaDao = new HistoricoFerramentaDao();
                historicoFerramentaDao.buscar(idHistoricoFerramenta);

                historicoFerramentaDao.setObservacao(jTextArea1.getText());
                historicoFerramentaDao.setDtPrevisaoDevolucao(Format.formatVisualDateToTimestamp(jFormattedTextField2.getText()));

                if (SituacaoHistoricoFerramenta.DEVOLVIDA == EnumSituacaoHistoricoFerramenta.ConvertStringEnum(jComboBox3.getSelectedItem().toString())) {
                    historicoFerramentaDao.setDtDevolucao(Format.formatVisualDateToTimestamp(jFormattedTextField5.getText()));
                    historicoFerramentaDao.setSituacao(SituacaoHistoricoFerramenta.DEVOLVIDA);

                    LinkedList<FerramentaHistoricoDao> listaFerramentaHistorico = FerramentaHistoricoDao.listarFerramentaHistoricoPorIdHistorico(idHistoricoFerramenta);
                    for (int i = 0; i < listaFerramentaHistorico.size(); i++) {
                        FerramentaHistoricoDao ferramentaHistoricoDao = listaFerramentaHistorico.get(i);
                        ferramentaHistoricoDao.setSituacao(SituacaoFerramentaHistoricoFerramenta.DESATIVADO);
                        ferramentaHistoricoDao.atualizar();
                    }

                    for (int i = 0; i < listaFerramentas.size(); i++) {
                        FerramentaDao ferramentaDao = listaFerramentas.get(i);
                        ferramentaDao.setIdFuncionario(0);
                        ferramentaDao.atualizar();
                    }
                }

                historicoFerramentaDao.atualizar();

                JanelaLogin.connection.commit();
                JOptionPane.showMessageDialog(null, "Categoria editada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void adicionarFerramenta(boolean editar) {
        try {
            int idFerramentaBuscada = FerramentaDao.getIdFerramentaPorIdentificador(jTextField8.getText());
            if (idFerramentaBuscada != 0) {
                FerramentaDao ferramentaDao = new FerramentaDao();
                ferramentaDao.buscar(idFerramentaBuscada);
                if (!buscarFerramentaNaLista(ferramentaDao)) {
                    if (ferramentaDao.getIdFuncionario() == 0) {
                        if (!editar) {
                            listaFerramentas.add(ferramentaDao);
                        } else {
                            listaFerramentas.set(index, ferramentaDao);
                        }
                        limparCamposFerramentas();

                        buscarTabela();
                    } else {
                        FuncionarioDao funcionarioDao = new FuncionarioDao();
                        funcionarioDao.buscar(ferramentaDao.getIdFuncionario());

                        JOptionPane.showMessageDialog(null, "Esta ferramenta não está no estoque, pois ela está na posse do funcionário (" + funcionarioDao.getIdentificador() + ").", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Esta ferramenta já está na sua lista.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }

            } else {
                JOptionPane.showMessageDialog(null, "Ferramenta não encontrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private boolean buscarFerramentaNaLista(FerramentaDao ferramentaBuscada) {
        for (int i = 0; i < listaFerramentas.size(); i++) {
            FerramentaDao ferramentaDao = listaFerramentas.get(i);
            if (ferramentaDao.getId() == ferramentaBuscada.getId()) {
                return true;
            }
        }
        return false;
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        HistoricoFerramentaDao historicoFerramentaDao = new HistoricoFerramentaDao();
        historicoFerramentaDao.buscar(idHistoricoFerramenta);

        FuncionarioDao funcionarioDao = new FuncionarioDao();
        funcionarioDao.buscar(historicoFerramentaDao.getIdFuncionario());
        jTextField1.setText(funcionarioDao.getIdentificador());

        jFormattedTextField1.setText(Format.formatarTimeStampApresentacao(historicoFerramentaDao.getDtEntrega()));
        jFormattedTextField2.setText(Format.formatarTimeStampApresentacao(historicoFerramentaDao.getDtPrevisaoDevolucao()));
        jTextField4.setText(historicoFerramentaDao.getJustificativa());
        jTextArea1.setText(historicoFerramentaDao.getObservacao());

        LinkedList<FerramentaHistoricoDao> listaFerramentaHistorico = FerramentaHistoricoDao.listarFerramentaHistoricoPorIdHistorico(historicoFerramentaDao.getId());

        for (int i = 0; i < listaFerramentaHistorico.size(); i++) {
            FerramentaHistoricoDao ferramentaHistoricoDao = listaFerramentaHistorico.get(i);
            FerramentaDao ferramentaDao = new FerramentaDao();
            ferramentaDao.buscar(ferramentaHistoricoDao.getIdFerramenta());
            listaFerramentas.add(ferramentaDao);
        }

        if (historicoFerramentaDao.getSituacao() == SituacaoHistoricoFerramenta.DEVOLVIDA) {
            jFormattedTextField2.setEnabled(false);
            jFormattedTextField5.setEnabled(false);
            jTextField4.setEnabled(false);
            jTextArea1.setEnabled(false);
            jButton1.setEnabled(false);
            jComboBox3.setEnabled(false);
        }

        buscarTabela();
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {
        autoCompletarFuncionario = new AutoComplete(jList1, jScrollPane2, jTextField1);
        listaFerramentas = new LinkedList<FerramentaDao>();

        autoCompletarIdentificadorFerramenta = new AutoComplete(jList2, jScrollPane3, jTextField8);
        autoCompletarNomeFerramenta = new AutoComplete(jList3, jScrollPane5, jTextField5);


        configureTable();

        LinkedList<String> listaSituacaoHistoricoFerramenta = EnumSituacaoHistoricoFerramenta.ListaStringSituacao();
        for (int i = 0; i < listaSituacaoHistoricoFerramenta.size(); i++) {
            jComboBox3.addItem(listaSituacaoHistoricoFerramenta.get(i));
        }
        if (idHistoricoFerramenta != 0) { // Edição 
            carregarInformacoes();
            jTextField1.setEnabled(false);
            jFormattedTextField1.setEnabled(false);
            jTextField4.setEnabled(false);
            jTextField8.setEnabled(false);
            jButton2.setEnabled(false);
            jRadioButton1.setEnabled(false);
            jRadioButton2.setEnabled(false);
        } else {
            jFormattedTextField1.setEnabled(false);
            jFormattedTextField5.setEnabled(false);
            jFormattedTextField5.setText("");
            jComboBox3.setEnabled(false);
            jComboBox3.setSelectedItem(EnumSituacaoHistoricoFerramenta.SituacaoHistoricoFerramenta.PENDENTE);
        }

        configurarCamposHistoricoFerramentas();
    }

    private void selecionarFerramenta(boolean opcao) {
        int idFerramentaDao = (opcao) ? FerramentaDao.getIdFerramentaPorIdentificador(jTextField8.getText()) : FerramentaDao.getIdFerramentaPorNome(jTextField5.getText());
        if (idFerramentaDao != 0) {
            FerramentaDao ferramentaDao = new FerramentaDao();
            ferramentaDao.buscar(idFerramentaDao);
            if (opcao) {
                jTextField5.setText(ferramentaDao.getNome());
            } else {
                jTextField8.setText(ferramentaDao.getIdentificador());
            }
        } else {
            if (opcao) {
                jTextField5.setText("");
            } else {
                jTextField8.setText("");
            }
        }
    }

    public void imprimir(int id) {
        try {
            HashMap parameters = new HashMap();

            parameters.put("idHistoricoFerramenta", id);
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("manager/modulo/ferramenta/relatorio/HistoricoFerramenta.jasper");
            Connection connection = JanelaLogin.getConnection();
            JasperPrint relat = JasperFillManager.fillReport(is, parameters, connection);
            JasperViewer.viewReport(relat, false);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Histórico Ferramenta");
        }

    }

    public void modificarOpcaoAutocompletar(boolean opcao) {
        jTextField8.setEnabled(opcao);
        jTextField5.setEnabled(!opcao);
        jScrollPane3.setVisible(false);
        jScrollPane5.setVisible(false);
        limparCamposFerramentas();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new manager.helpers.validation.TextFieldValidator(80,-1,true,true,"text",jLabel1);
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jTextField8 = new TextFieldValidator(-1, -1, true, true, "text", jLabel13);
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(-1, -1, true, true, "text", jLabel8);
        jScrollPane5 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jFormattedTextField1 = new FormatedFieldValidator(true, true, "date", jLabel6);
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(100, -1, true, true, "text", jLabel7);
        jComboBox3 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jFormattedTextField5 = new FormatedFieldValidator(true, true, "date", jLabel16);
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel44 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jFormattedTextField2 = new FormatedFieldValidator(true, true, "date", jLabel9);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("HISTÓRICO DE FERRAMENTAS");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(601, 450));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Funcionário");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 20, 150, 14);

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });
        jPanel1.add(jTextField1);
        jTextField1.setBounds(20, 40, 285, 20);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("LISTA DE FERRAMENTAS"));
        jPanel2.setLayout(null);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setToolTipText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(460, 30, 30, 30);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton3.setToolTipText("Cancelar");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(540, 30, 30, 30);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Identificador");
        jPanel2.add(jLabel13);
        jLabel13.setBounds(30, 20, 90, 14);

        jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField8KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField8);
        jTextField8.setBounds(10, 40, 150, 20);

        jScrollPane3.setVisible(false);

        jList2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList2MouseReleased(evt);
            }
        });
        jList2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList2KeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jList2);

        jPanel2.add(jScrollPane3);
        jScrollPane3.setBounds(10, 60, 150, 50);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/remove.png"))); // NOI18N
        jButton4.setToolTipText("Remover");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);
        jButton4.setBounds(500, 30, 30, 30);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Ferramenta");
        jPanel2.add(jLabel8);
        jLabel8.setBounds(185, 20, 80, 14);

        jTextField5.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField5.setEnabled(false);
        jTextField5.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField5FocusLost(evt);
            }
        });
        jTextField5.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField5KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField5);
        jTextField5.setBounds(165, 40, 290, 20);

        jScrollPane5.setVisible(false);

        jList3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList3MouseReleased(evt);
            }
        });
        jList3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList3KeyReleased(evt);
            }
        });
        jScrollPane5.setViewportView(jList3);

        jPanel2.add(jScrollPane5);
        jScrollPane5.setBounds(165, 60, 290, 50);

        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(10, 70, 560, 100);

        jRadioButton1.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setSelected(true);
        jRadioButton1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton1ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton1);
        jRadioButton1.setBounds(5, 17, 20, 21);

        jRadioButton2.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton2);
        jPanel2.add(jRadioButton2);
        jRadioButton2.setBounds(160, 17, 20, 21);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(10, 190, 580, 180);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(10, 380, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(120, 380, 100, 23);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Entrega");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(310, 20, 80, 14);

        jFormattedTextField1.setNextFocusableComponent(jTextField4);
        jPanel1.add(jFormattedTextField1);
        jFormattedTextField1.setBounds(310, 40, 75, 20);

        jScrollPane2.setVisible(false);

        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList1MouseReleased(evt);
            }
        });
        jList1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList1KeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jList1);

        jPanel1.add(jScrollPane2);
        jScrollPane2.setBounds(20, 60, 285, 50);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Justificativa");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(160, 70, 70, 14);

        jTextField4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField4FocusLost(evt);
            }
        });
        jPanel1.add(jTextField4);
        jTextField4.setBounds(160, 90, 430, 20);

        jPanel1.add(jComboBox3);
        jComboBox3.setBounds(20, 90, 130, 20);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Situação");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(20, 70, 70, 14);

        jLabel16.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel16.setText("Devolução");
        jPanel1.add(jLabel16);
        jLabel16.setBounds(510, 20, 59, 14);

        jFormattedTextField5.setNextFocusableComponent(jTextField4);
        jPanel1.add(jFormattedTextField5);
        jFormattedTextField5.setBounds(510, 40, 80, 20);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(2);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane4.setViewportView(jTextArea1);
        jTextArea1.setDocument(new FixedLengthDocument(200));

        jPanel1.add(jScrollPane4);
        jScrollPane4.setBounds(20, 130, 570, 50);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Observação");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 110, 80, 14);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Previsão Devolução");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(390, 20, 115, 14);

        jFormattedTextField2.setNextFocusableComponent(jTextField4);
        jPanel1.add(jFormattedTextField2);
        jFormattedTextField2.setBounds(390, 40, 115, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 600, 410);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposHistoricoFerramentas();
        if (fieldValidadeList.size() == 0) {
            if (idHistoricoFerramenta == 0) {
                adicionarHistorioFerramenta();
            } else {
                editarHistoricoFerramenta();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (idFerramenta == 0) {
            adicionarFerramenta(false);
        } else {
            adicionarFerramenta(true);
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        limparCamposFerramentas();
}//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                if (FuncionarioDao.getIdFuncionarioByIdentificador(jTextField1.getText()) != 0) {
                    jTextField1.transferFocus();
                }
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarFuncionario.getjScrollPane().isVisible()) {
                    autoCompletarFuncionario.getjList().setSelectedIndex(0);
                    autoCompletarFuncionario.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarFuncionario.getSearchWord().equals(jTextField1.getText())) {
                    autoCompletarFuncionario.setSearchWord(jTextField1.getText());
                    autoCompletarFuncionario.update(new FuncionarioDao().buscar("Identificador", jTextField1.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jList1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList1KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarFuncionario.setSearchWord(autoCompletarFuncionario.getjList().getSelectedValue().toString());
            autoCompletarFuncionario.getjScrollPane().setVisible(false);
            jFormattedTextField2.requestFocus();
        }
    }//GEN-LAST:event_jList1KeyReleased

    private void jList1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseReleased
        autoCompletarFuncionario.setSearchWord(autoCompletarFuncionario.getjList().getSelectedValue().toString());
        autoCompletarFuncionario.getjScrollPane().setVisible(false);
        jFormattedTextField2.requestFocus();
    }//GEN-LAST:event_jList1MouseReleased

    private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                if (FerramentaDao.getIdFerramentaPorIdentificador(jTextField8.getText()) != 0) {
                    jTextField8.transferFocus();
                    selecionarFerramenta(jRadioButton1.isSelected());
                }
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarIdentificadorFerramenta.getjScrollPane().isVisible()) {
                    autoCompletarIdentificadorFerramenta.getjList().setSelectedIndex(0);
                    autoCompletarIdentificadorFerramenta.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarIdentificadorFerramenta.getSearchWord().equals(jTextField8.getText())) {
                    autoCompletarIdentificadorFerramenta.setSearchWord(jTextField8.getText());
                    autoCompletarIdentificadorFerramenta.update(new FerramentaDao().buscar("Identificador", jTextField8.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField8KeyReleased

    private void jTextField4FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField4FocusLost
//        jTextField9.setText(jTextField4.getText());
//        ((TextFieldValidator) jTextField9).validarCampo();
    }//GEN-LAST:event_jTextField4FocusLost

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        listaFerramentas.remove(index);
        limparCamposFerramentas();
        buscarTabela();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTextField5FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField5FocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField5FocusLost

    private void jList2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList2KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarIdentificadorFerramenta.setSearchWord(autoCompletarIdentificadorFerramenta.getjList().getSelectedValue().toString());
            autoCompletarIdentificadorFerramenta.getjScrollPane().setVisible(false);
            selecionarFerramenta(jRadioButton1.isSelected());
        }
    }//GEN-LAST:event_jList2KeyReleased

    private void jList2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseReleased
        autoCompletarIdentificadorFerramenta.setSearchWord(autoCompletarIdentificadorFerramenta.getjList().getSelectedValue().toString());
        autoCompletarIdentificadorFerramenta.getjScrollPane().setVisible(false);
        selecionarFerramenta(jRadioButton1.isSelected());
    }//GEN-LAST:event_jList2MouseReleased

    private void jList3MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList3MouseReleased
        autoCompletarNomeFerramenta.setSearchWord(autoCompletarNomeFerramenta.getjList().getSelectedValue().toString());
        autoCompletarNomeFerramenta.getjScrollPane().setVisible(false);
        selecionarFerramenta(jRadioButton1.isSelected());
    }//GEN-LAST:event_jList3MouseReleased

    private void jList3KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList3KeyReleased
        autoCompletarNomeFerramenta.setSearchWord(autoCompletarNomeFerramenta.getjList().getSelectedValue().toString());
        autoCompletarNomeFerramenta.getjScrollPane().setVisible(false);
        selecionarFerramenta(jRadioButton1.isSelected());
    }//GEN-LAST:event_jList3KeyReleased

    private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton1ItemStateChanged
        modificarOpcaoAutocompletar(jRadioButton1.isSelected());
    }//GEN-LAST:event_jRadioButton1ItemStateChanged

    private void jTextField5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField5KeyReleased
         try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                if (FerramentaDao.getIdFerramentaPorNome(jTextField5.getText()) != 0) {
                    jTextField5.transferFocus();
                    selecionarFerramenta(jRadioButton1.isSelected());
                }
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarNomeFerramenta.getjScrollPane().isVisible()) {
                    autoCompletarNomeFerramenta.getjList().setSelectedIndex(0);
                    autoCompletarNomeFerramenta.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarNomeFerramenta.getSearchWord().equals(jTextField5.getText())) {
                    autoCompletarNomeFerramenta.setSearchWord(jTextField5.getText());
                    autoCompletarNomeFerramenta.update(new FerramentaDao().buscar("Nome", jTextField5.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField5KeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JFormattedTextField jFormattedTextField2;
    private javax.swing.JFormattedTextField jFormattedTextField5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField8;
    // End of variables declaration//GEN-END:variables
}
